#include "PageManager.hpp"
#include "Page.hpp"
#include "zj_logger.h"


PageManager::PageManager(AppState* app_state)
{
    current_page = 0;
    new_page = 0;
    exit_requested = false;

    this->app_state = app_state;
}

PageManager::~PageManager()
{
}

void PageManager::first_page(Page* first_page)
{
    new_page = first_page;
    zj_logger_d("PageManager", "first_page()");
}

void PageManager::request_exit()
{
    exit_requested = true;
    zj_logger_d("PageManager", "request_exit()");
}

void PageManager::request_page(Page* new_page)
{
    this->new_page = new_page;
    zj_logger_d("PageManager", "request_page()");
}

void PageManager::do_step()
{
    // 换页
    if (new_page) {
        if (current_page)
            delete current_page;
        current_page = new_page;
        new_page = nullptr;
        zj_logger_d("PageManager", "page name: %s", current_page->page_name.c_str());
        current_page->app_state = app_state;
        current_page->init();
    }

    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        if (current_page)
            current_page->handle(event);
    }
    if (current_page)
        current_page->update();

    // 请求退出
    if (exit_requested) {
        if (current_page)
            delete current_page;
        current_page = nullptr;
        // 后续交给主程序
    }
}

void PageManager::do_draw()
{
    if (current_page) {
        int w, h;
        SDL_GetRendererOutputSize(app_state->renderer, &w, &h);

        float percent = 0.95;
        SDL_Rect canvas;
        canvas.x = (1.0-percent)/2.0*w;
        canvas.y = (1.0-percent)/2.0*h;
        canvas.w = w*percent;
        canvas.h = h*percent;
        current_page->draw(canvas);

        SDL_RenderPresent(app_state->renderer);
    }
}
